package com.lhc.controller;

import com.alibaba.druid.util.StringUtils;
import com.lhc.controller.viewObject.UserVo;
import com.lhc.error.BusniessException;
import com.lhc.error.CommonError;
import com.lhc.error.EmBussinessError;
import com.lhc.response.CommonReturnType;
import com.lhc.service.UserService;
import com.lhc.service.model.UserModel;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;


@Controller("user")
@RequestMapping("/user")
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private HttpServletRequest request;

    //通过手机号和密码登录
    @RequestMapping(value = "/login",method = {RequestMethod.POST},consumes = CONTENT_TYPE_FORMED)
    @ResponseBody
    public CommonReturnType login(@RequestParam("telphone") String telphone,@RequestParam("password") String password) throws BusniessException, NoSuchAlgorithmException {
        if (StringUtils.isEmpty(telphone) || StringUtils.isEmpty(password)){
            throw new BusniessException(EmBussinessError.PARAMETER_VALIDATION_ERROR);
        }
        UserModel userModel = userService.validateLogin(telphone, EncodeByMD5(password));
        //将登录的用户放进session中
        this.request.getSession().setAttribute("IS_LOGIN",true);
        this.request.getSession().setAttribute("LOGIN_USER",userModel);
        return CommonReturnType.create(null);
    }



    //注册功能实现
    @RequestMapping(value = "/register",method = {RequestMethod.POST},consumes = CONTENT_TYPE_FORMED)
    @ResponseBody
    public CommonReturnType register(
            @RequestParam("telphone") String telphone,
            @RequestParam("name") String name,
            @RequestParam("gender") Integer gender,
            @RequestParam("age") Integer age,
            @RequestParam("otpCode") String otpCode,
            @RequestParam("password") String password
    ) throws BusniessException, NoSuchAlgorithmException {
        //验证手机号和姓名是否符合
        String sessionOtpCode = (String) this.request.getSession().getAttribute(telphone);
        if (!StringUtils.equals(otpCode,sessionOtpCode)){
            throw new BusniessException(EmBussinessError.PARAMETER_VALIDATION_ERROR,"短信验证码不符合");
        }
        //用户注册流程
        UserModel userModel = new UserModel();
        userModel.setTelphone(telphone);
        userModel.setName(name);
        userModel.setGender(new Byte(String.valueOf(gender.intValue())));
        userModel.setAge(age);
        userModel.setRegisterMode("byphone");
        userModel.setEncrptPassword(this.EncodeByMD5(password));
        userService.register(userModel);
        return CommonReturnType.create(null);
    }


    //获取手机验证码
    @RequestMapping(value = "/getOtp",method = {RequestMethod.POST},consumes = CONTENT_TYPE_FORMED)
    @ResponseBody
    public CommonReturnType getOtp(@RequestParam("telphone") String telphone) {
        //生成一个随机数与手机号绑定
        Random random = new Random();
        int nextInt = random.nextInt(99999);
        nextInt += 10000;
        String otpCode = String.valueOf(nextInt);
        //绑定otpCode与手机号
        request.getSession().setAttribute(telphone,otpCode);
        System.out.println("otpCode:" + otpCode + " & telphone:" +  telphone);
        return CommonReturnType.create(null);
    }

    //通过id查询
    @RequestMapping("/getUserById/{id}")
    @ResponseBody
    public CommonReturnType getUserById(@PathVariable("id") Integer id) throws BusniessException {
        UserModel userModel = userService.selectByPrimaryKey(id);
        if (userModel == null) {
            throw new BusniessException(EmBussinessError.USER_NOT_EXIST);
        }
        UserVo userVo = convertFromModel(userModel);
        return CommonReturnType.create(userVo);
    }
    //从model对象中转换uservo
    private UserVo convertFromModel(UserModel userModel) {
        UserVo userVo = new UserVo();
        if (userModel == null) {
            return null;
        }
        BeanUtils.copyProperties(userModel, userVo);
        return userVo;
    }
    //密码加密
    private String EncodeByMD5(String password) throws NoSuchAlgorithmException {
        //确定计算方法
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64Encoder = new BASE64Encoder();
        //加密
        String encode = base64Encoder.encode(md5.digest(password.getBytes()));
        return encode;
    }

}
